package org.tg.common.auth;


import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.tg.common.constant.RedisConst;
import org.tg.common.exception.CustomExceptionHandler;
import org.tg.common.result.Result;
import org.tg.common.result.ResultCodeEnum;
import org.tg.common.util.helper.JwtHelper;
import org.tg.vo.acl.AdminLoginVo;
import org.tg.vo.user.UserLoginVo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author Glow
 * @Date 2023-07-13 15:22:31
 * @Description
 * @Version 1.0
 */
public class UserLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    public UserLoginInterceptor(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        this.getUserLoginVo(request);
        return true;
    }

    private void getUserLoginVo(HttpServletRequest request) {
       // System.out.println("当前拦截请求路径："+request.getRequestURL());
        String checkPath = request.getRequestURI();
        System.out.println("当前拦截请求路径："+checkPath);
//        System.out.println("当前拦截请求路径："+request.getContextPath());
        //从请求头获取token
        String token = request.getHeader("token");
        String usertype = request.getHeader("usertype");
//        System.out.println("token:"+token);
//        System.out.println("usertype:"+usertype);

        //判断token不为空
        if((!StringUtils.isEmpty(token))&&("wxuser".equals(usertype))) {
            //从token获取userId
            Long userId = JwtHelper.getUserId(token);
            //根据userId到Redis获取用户信息
            UserLoginVo userLoginVo = (UserLoginVo)redisTemplate.opsForValue()
                    .get(RedisConst.USER_LOGIN_KEY_PREFIX + userId);
            //获取数据放到ThreadLocal里面
            if(userLoginVo != null) {
                AuthContextHolder.setUserId(userLoginVo.getUserId());
                AuthContextHolder.setWareId(userLoginVo.getWareId());
                AuthContextHolder.setUserLoginVo(userLoginVo);
            }
        }
        //管理端
        if((!StringUtils.isEmpty(token))&&("adminuser".equals(usertype))) {
            //从token获取userId
            Long adminId = JwtHelper.getAdminUserId(token);
            Long wareId = JwtHelper.getAdminwareId(token)  ;

            //根据userId到Redis获取用户信息
            AdminLoginVo adminLoginVo = (AdminLoginVo)redisTemplate.opsForValue()
                    .get(RedisConst.ADMIN_LOGIN_KEY_PREFIX + adminId);
            //获取数据放到ThreadLocal里面
            if(adminLoginVo != null) {
                AuthContextHolder.setAdminId(adminLoginVo.getAdminId());
                AuthContextHolder.setWareId(wareId);
               AuthContextHolder.setRoleId(adminLoginVo.getRoleId());
                AuthContextHolder.setAdminLoginVo(adminLoginVo);
            }
            //获取用户可通过的请求路径
            List<String> allAccessPath = (List<String>)redisTemplate.opsForValue().get
                    (RedisConst.ADMIN_ROLE_PATH_PREFIX+adminId);

            //鉴权路径
            AntPathMatcher matcher = new AntPathMatcher();
            System.out.println("byd鉴权"+matcher.match("/admin/acl/index/logout",checkPath));
            System.out.println("byd鉴权"+matcher.match("/admin/acl/index/info",checkPath));
            if(
                    !(
                            matcher.match("/admin/acl/index/logout",checkPath)||
                            matcher.match("/admin/acl/index/info",checkPath)
                    )
            )
            //AntPathMatcher正则表达式参考
                //https://blog.csdn.net/JokerLJG/article/details/127751174
            {
                if(!CollectionUtils.isEmpty(allAccessPath))
                {
                    boolean isAccess = false;
                    for(String check : allAccessPath)
                    {
                        if(matcher.match(check,checkPath))
                        {
                            System.out.println("路径通过为："+check);
                            isAccess = true;
                        }
                    }
                        if(!isAccess)
                        {
                            throw  new CustomExceptionHandler(ResultCodeEnum.PERMISSION);
                        }

                }
            }




        }

    }
}

